package com.study.shiro;

import com.study.config.ShiroConfig;
import com.study.dbo.ManagerDO;
import com.study.service.ManagerService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


public class AuthRealm extends AuthorizingRealm{


	@Autowired
	@Qualifier("managerService")
	private ManagerService managerService;

	//授权   当页面出现Shiro标签时，就会执行授权方法
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection pc) {
		System.out.println("授权");
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.addRole("admin");
		return info;
	}

	@Override
	//认证   token 代表用户在界面输入的用户名和密码
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		System.out.println("认证");
//1.向下转型
		UsernamePasswordToken upToken = null;
		if (token instanceof UsernamePasswordToken) {
			upToken = (UsernamePasswordToken) token;
		} else {
			return null;
		}
		//2.调用业务方法，实现根据账号查询
		ManagerDO managerDO = managerService.findByAccount(upToken.getUsername());
		if (managerDO == null) {
			//没有该用户
			throw new UnknownAccountException(); //用户名错误
		}
		if (managerDO.getManagerLocked()) {
			throw new LockedAccountException();
		}
		AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(managerDO, managerDO.getManagerPasswd(), this.getName());
		managerDO.setManagerPasswd(null);
		return authenticationInfo;
	}
}
